package com.sync.syncmasterdata.product.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.dingrobot.service.DingRobotService;
import com.sync.syncmasterdata.product.entity.bip.BipProductEntity;
import com.sync.syncmasterdata.product.pojo.bip.ProductAssign;
import com.sync.syncmasterdata.product.pojo.bip.ProductForBip;
import com.sync.syncmasterdata.product.pojo.bip.ProductProdForBip;
import com.sync.syncmasterdata.product.pojo.bip.ProductStockForBip;
import com.sync.syncmasterdata.product.repository.bip.BipMaterialRepository;
import com.sync.syncmasterdata.pubdomain.BipResponse;
import com.sync.syncmasterdata.util.BipRequestUtil;
import com.sync.syncmasterdata.util.NormalUtil;
import com.sync.syncmasterdata.vendor.pojo.bip.SupplierAssign;
import lombok.extern.slf4j.Slf4j;
import nccloud.open.api.auto.token.itf.IAPIUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Bip系统 物料相关服务
 * 1.先新建
 * 2.再分配
 * 3.分配后调整tab页信息
 * todo:物料的controller层需要完善, 根据具体需求
 *
 * 注意:
 * // todo:批次管理+批号管理必须要Y
 * // todo:表单增加 库存页签 根据检验结果入库+免检 勾选 (测试结果,这两个互斥)
 * // todo:生产页签 物料形态(半成品+产成品勾选成本对象,采购品不用勾选成本对象),表单增加
 */
@Service
@Slf4j
public class BipProductServiceImpl {

    @Autowired
    private BipRequestUtil bipRequestUtil;

    @Autowired
    private BipMaterialRepository bipMaterialRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private DingRobotService dingRobotService;

    private String ACCESSTOKEN;

    /**
     * 请求新增bip 物料
     * @param product
     */
    public String addProduct(ProductForBip product) {
        try {
            IAPIUtils iapiUtils= bipRequestUtil.getAPIUtil();
            String url = "nccloud/api/uapbd/material/material/add";
            iapiUtils.setApiUrl(url);
            this.ACCESSTOKEN = iapiUtils.getToken();
            Map<String, Object> req = bipRequestUtil.requestMap("ufinterface", product);
            String params = objectMapper.writeValueAsString(req);
            String ret = iapiUtils.getAPIRetrun(this.ACCESSTOKEN, params);
            JSONObject retJson = new JSONObject(ret);
            if (retJson.getBoolean("success")) {
                JSONObject innerJson = retJson.getJSONObject("data").getJSONObject("ufinterface");
                if (innerJson.getString("successful").equals("Y")) {
                    JSONObject _arrayJson = (JSONObject)innerJson.getJSONArray("sendresult").get(0);
                    return _arrayJson.getString("content");
                }
            }else{
                dingRobotService.simpleDingSendMsg("推送Bip物料信息（新增）出错：" + objectMapper.writeValueAsString(retJson),new String[]{"15267167276"});
                log.info("请求新增bip 物料信息失败" + objectMapper.writeValueAsString(retJson));
            }
        } catch (Exception e) {
            e.printStackTrace();
            dingRobotService.simpleDingSendMsg("推送Bip物料信息（新增）出错：" + e.toString(),new String[]{"15267167276"});
        }
        return null;
    }

    /**
     * 获取客户Code 使用PKCustomer值  因为返回Json中只有ID.没有code,并赋值对象
     * @param pkMaterial
     * @return
     */
    public String getProductCode(String pkMaterial) {
        BipProductEntity entity=bipMaterialRepository.getProductCode(pkMaterial);
        if (StringUtils.isNotBlank(entity.getCode())) {
            return entity.getCode();
        }
        return null;
    }

    /**
     * 物料分配
     * @param materialCode 物料编码
     * @param orgs 分配组织
     * @return
     */
    public boolean assignMaterial(String materialCode,String[] orgs){
        try {
            IAPIUtils iapiUtils= bipRequestUtil.getAPIUtil();
            String url="nccloud/api/uapbd/material/material/assignMaterial";
            iapiUtils.setApiUrl(url);
            ProductAssign.AssignData assignData=ProductAssign.AssignData.builder().code(materialCode).assignorgs(Arrays.asList(orgs)).build();
            ProductAssign productAssign=ProductAssign.builder().data(assignData).build();
            String params = objectMapper.writeValueAsString(NormalUtil.assembleMap("ufinterface",productAssign));
            String ret = iapiUtils.getAPIRetrun(this.ACCESSTOKEN, params);
            BipResponse<String> bipResponse=objectMapper.readValue(ret,BipResponse.class);
            if(bipResponse.getSuccess()){
                return true;
            }else{
                dingRobotService.simpleDingSendMsg("推送Bip物料信息后分配（新增）出错：",new String[]{"15267167276"});
                return false;
            }
        } catch (Exception e) {
            log.info("推送物料分配异常");
            dingRobotService.simpleDingSendMsg("推送Bip物料信息后分配（新增）出错："+e.toString(),new String[]{"15267167276"});
            return false;
        }
    }


    /**
     * 分配后新增物料-库存Tab页信息 循环处理
     */
    public boolean stockAdd(String[] orgs, ProductStockForBip productStockForBip) {
        try {
            IAPIUtils iapiUtils= bipRequestUtil.getAPIUtil();
//            String accessToken = iapiUtils.getToken();
            String url="nccloud/api/uapbd/material/materialstock/add";
            iapiUtils.setApiUrl(url);
            for (String org : orgs) {
                //两个组织字段要一起改
                productStockForBip.getBill().getBillhead().setPk_org_m(org);
                productStockForBip.getBill().getBillhead().setPk_org(org);
                Map<String, Object> ufinterface = NormalUtil.assembleMap("ufinterface", productStockForBip);
                String ret = iapiUtils.getAPIRetrun(this.ACCESSTOKEN, objectMapper.writeValueAsString(ufinterface));
                BipResponse<HashMap> bipResponse = objectMapper.readValue(ret, BipResponse.class);
                Map<String, Object> resUfinterface = bipResponse.getData();
                if(resUfinterface instanceof Map){
                    Map<String, Object> _res =(Map<String,Object>) resUfinterface.get("ufinterface");
                    if (_res.get("successful").equals("N")) {
                        dingRobotService.simpleDingSendMsg("推送Bip物料(" + org + ")创建库存信息出错信息后分配（新增）出错,需要手动修改库存信息Tab：", new String[]{"15267167276"});
                    }
                }else{
                    dingRobotService.simpleDingSendMsg("推送Bip物料(" + org + ")创建库存信息出错信息后分配（新增）出错,需要手动修改库存信息Tab：", new String[]{"15267167276"});
                }
            }
            return true;
        } catch (Exception e) {
            dingRobotService.simpleDingSendMsg("推送Bip物料创建库存信息出错信息后分配（新增）异常：", new String[]{"15267167276"});
            return false;
        }
    }

    /**
     * 分配后新增物料-生产Tab页信息 需要 循环处理
     */
    public boolean prodAdd(String[] orgs, ProductProdForBip productProdForBip){
        try {
            IAPIUtils iapiUtils= bipRequestUtil.getAPIUtil();
//            String accessToken = iapiUtils.getToken();
            String url="nccloud/api/uapbd/material/materialprod/add";
            iapiUtils.setApiUrl(url);
            for (String org : orgs) {
                //两个组织字段要一起改
                productProdForBip.getBill().getBillhead().setPk_org_m(org);
                productProdForBip.getBill().getBillhead().setPk_org(org);
                Map<String, Object> ufinterface = NormalUtil.assembleMap("ufinterface", productProdForBip);
                String ret = iapiUtils.getAPIRetrun(this.ACCESSTOKEN, objectMapper.writeValueAsString(ufinterface));
                BipResponse<HashMap> bipResponse = objectMapper.readValue(ret, BipResponse.class);
                Map<String, Object> resUfinterface = bipResponse.getData();
                if(resUfinterface instanceof Map){
                    Map<String, Object> _res =(Map<String,Object>) resUfinterface.get("ufinterface");
                    if (_res.get("successful").equals("N")) {
                        dingRobotService.simpleDingSendMsg("推送Bip物料(" + org + ")创建生产信息出错信息后分配（新增）出错,需要手动修改库存信息Tab：", new String[]{"15267167276"});
                    }
                }else{
                    dingRobotService.simpleDingSendMsg("推送Bip物料(" + org + ")创建生产信息出错信息后分配（新增）出错,需要手动修改库存信息Tab：", new String[]{"15267167276"});
                }
            }
            return true;
        } catch (Exception e) {
            dingRobotService.simpleDingSendMsg("推送Bip物料创建生产信息出错信息后分配（新增）异常：", new String[]{"15267167276"});
            return false;
        }
    }

}
